from odoo import fields, models, api
from odoo.exceptions import UserError, ValidationError

REL_TYPE = [('address', '地址'), ('contact', '联系人')]
ADDRESS_TYPE = [('residential', '个人'), ('commercial', '公司')]


class RESPartnerInheritForCustomer(models.Model):
    _inherit = 'res.partner'

    # 该字段用于判断当前res.partner记录是当作地址是用还是联系人使用，并用于search
    rel_type = fields.Selection(string='关联类型', selection=REL_TYPE, compute='_depends_rel_type', store=True)
    area_code = fields.Char(string='区号')


    default_address = fields.Boolean(string='默认地址', default=False)
    address_type = fields.Selection(string='地址类型', selection=ADDRESS_TYPE, default=ADDRESS_TYPE[0][0])
    contact_company_name = fields.Char(string='公司名称')

    customer_address_id = fields.Many2one(string='地址关联客户', comodel_name='rp.customer', ondelete='cascade')

    customer_contact_id = fields.Many2one(string='联系人关联客户', comodel_name='rp.customer', ondelete='cascade')

    @api.depends('customer_address_id', 'customer_contact_id')
    def _depends_rel_type(self):
        for s in self:
            if all([s.customer_address_id, s.customer_contact_id]):
                raise UserError("同一条记录，不能既当地址又当联系人")
            elif all([s.customer_address_id, not s.customer_contact_id]):
                s.update({'rel_type': 'address'})
            elif all([not s.customer_address_id, s.customer_contact_id]):
                s.update({'rel_type': 'contact'})

    @api.constrains('default_address')
    def _check_default_address(self):
        """让每个客户只能有一个默认地址"""
        for s in self:
            if s.default_address:
                existing_default = self.search([('customer_address_id', '=', s.customer_address_id.id), ('default_address', '=', True), ('id', '!=', s.id)])
                for e in existing_default:
                    e.default_address = False

    @api.constrains('name', 'mobile', 'contact_company_name', 'country_id', 'state_id', 'city_id', 'county_id', 'street', 'postal_code_id')
    def _check_duplicates(self):
        """地址不能重复"""
        for rec in self:
            rcd = self.env[self._name].search([('customer_address_id', '=', rec.customer_address_id.id),
                                               ('name', '=', rec.name),
                                               ('mobile', '=', rec.mobile),
                                               ('address_type', '=', REL_TYPE[0][0]),
                                               ('contact_company_name', '=', rec.contact_company_name if rec.address_type == ADDRESS_TYPE[1][0] else False),
                                               ('country_id', '=', rec.country_id.id),
                                               ('state_id', '=', rec.state_id.id),
                                               ('city_id', '=', rec.city_id.id),
                                               ('county_id', '=', rec.county_id.id if rec.county_id else False),
                                               ('street', '=', rec.street),
                                               ('postal_code_id', '=', rec.postal_code_id.id)])
            if len(rcd) > 1:
                raise ValidationError("地址信息不允许重复记录")
